<?php

namespace App\Http\Controllers\Pay;


use App\Models\Order;

use Illuminate\Support\Facades\Config;
use Illuminate\Http\Request;
/**
 * 内部函数
 */
class ShouqianbaPaymentController
{


    /**
     * @param $vendor_sn
     * @param $vendor_key
     * @return null
     * 激活接口（只需要一次）
     */
    public function activate($vendor_sn, $vendor_key)
    {
        $api_domain = 'https://vsi-api.shouqianba.com';
        $url = $api_domain .'/terminal/activate';

        $config = Config::get('pay.payment');


        $params['app_id'] = $config['app_id'];            //app id，从服务商平台获取
        $params['code'] = $config['code'];              //激活码内容
        $params['device_id'] = $config['device_id'];         //设备唯一身份ID
dd($params);
        $ret = pre_do_execute($params, $url, $vendor_sn, $vendor_key);

        return $ret;

    }




    function pre_do_execute($params, $url, $terminal_sn, $terminal_key)
    {
        $j_params = json_encode($params);
        $sign = getSign($j_params . $terminal_key);
        $result = httpPost($url, $j_params, $sign, $terminal_sn);
        return $result;
    }



    function getSign($signStr)   //签名
    {
        $md5 = Md5($signStr);
        return $md5;
    }
    function httpPost($url, $body, $sign, $sn)   //头部请求规则
    {
        $header = array(
            "Format:json",
            "Content-Type: application/json",
            "Authorization:$sn" . ' ' . $sign
        );
        $result = do_execute($url, $body, $header);
        return $result;
    }

    function do_execute($url, $postfield, $header)
    {
        //    var_dump($url);echo '<br>';
        //    var_dump($postfield);echo '<br>';
        //    var_dump($header);echo '<br>';exit;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);  // 从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postfield);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
        $response = curl_exec($ch);
        //var_dump(curl_error($ch));  //查看报错信息
        file_put_contents('logs/web_api_' . date('Y-m-d') . '.txt', date("Y-m-d H:i:s", time()) . "===" . "返回：" . $response . "\n" . "请求应用参数：" . $postfield . "\n" . "\n" . "请求url：" . $url . "\n", FILE_APPEND);
//        var_dump($url);
//        echo '<br>';
//        var_dump($response);
//        exit;
        curl_close($ch);
        return $response;
    }

}
